<?php

namespace My\Model;

use Utuo\UtuoModel;

class WechatReplyModel extends UtuoModel {
	// 回复消息类型
	public $replyTypes = array(
			'text' => '文字',
			'news' => '图文',
			'link' => '链接' 
	);
	
	// 关注回复规则名称
	public $ruleSubscribe = '__rule_subscribe__';
	
	// 任意消息自动回复
	public $ruleAnything = '__rule_anything__';
	
	// 关注回复关键词
	public $keywordSubscribe = '__keyword_subscribe__';
	
	// 任意消息回复关键词
	public $keywordAnything = '__keyword_anything__';
	
	// 菜单回复
	public $ruleMenu = '__keyword_menu__';
	
	
	protected $_auto = array(
		array('link_url', 'htmlspecialchars_decode', self::MODEL_BOTH, 'function'),
	    array('text', 'htmlspecialchars_decode', self::MODEL_BOTH, 'function'),
	);
	
	// 自动验证
	protected $_validate = array(
			array(
					'rule',
					'require',
					'规则名不能为空' 
			),
			array(
					'keyword',
					'require',
					'规则关键词不能为空' 
			) 
	);
	
	// 处理关键词
	public function parseKeyword($keyword) {
		$keyword = explode(',', $keyword);
		$keyword = array_map('trim', $keyword);
		return "," . implode(',', $keyword) . ",";
	}
	
	/**
	 * 设置关注回复
	 *
	 * @param integer $cid
	 * @param string $title
	 * @param string $description
	 * @param string $pic
	 * @param string $url
	 */
	public function setSubscribeReply($cid, $title, $description, $pic, $url) {
		return $this->setLinkReply($cid, $this->ruleSubscribe, $this->keywordSubscribe, $title, $description, $pic, $url);
	}
	
	/**
	 * 设置任意消息回复
	 *
	 * @param integer $cid
	 * @param string $title
	 * @param string $description
	 * @param string $pic
	 * @param string $url
	 * @return boolean integer
	 */
	public function setAnythingReply($cid, $title, $description, $pic, $url) {
		return $this->setLinkReply($cid, $this->ruleAnything, $this->keywordAnything, $title, $description, $pic, $url);
	}
	
	/**
	 * 设置关键词消息回复
	 *
	 * @param integer $cid
	 * @param string $keyword
	 * @param string $title
	 * @param string $description
	 * @param string $pic
	 * @param string $url
	 * @return boolean integer
	 */
	public function setKeywordReply($cid, $rule, $keyword, $title, $description, $pic, $url) {
		return $this->setLinkReply($cid, $rule, $keyword, $title, $description, $pic, $url);
	}
	
	/**
	 * 添加微信图文链接回复规则
	 */
	public function setLinkReply($cid, $rule, $keyword, $title, $description, $pic, $url) {
		$data = array(
				'cid' => $cid,
				'rule' => $rule,
				'keyword' => $this->parseKeyword($keyword),
				'type' => 'link',
				'link_title' => $title,
				'link_description' => $description,
				'link_pic' => $pic,
				'link_url' => $url 
		);
		$id = $this->where(array(
				'cid' => $cid,
				'rule' => $rule 
		))->find();
		if ($id) {
			return $this->where("id=%d", $id)->save($data);
		}
		return $this->add($data);
	}
	
	/**
	 * 根据cid和rule查询自动回复内容
	 * 
	 * @param integer $cid
	 * @param string $rule
	 */
	public function getReply($cid, $rule) {
		return $this->where(array(
				'cid' => $cid,
				'rule' => $rule 
		))->find();
	}
}